package cn.jsony.pet.service.impl;

import cn.jsony.basic.config.BusinessException;
import cn.jsony.basic.service.IBaiduAiAuditService;
import cn.jsony.basic.util.*;
import cn.jsony.order.domain.OrderPetAcquisition;
import cn.jsony.order.mapper.OrderPetAcquisitionMapper;
import cn.jsony.org.domain.Employee;
import cn.jsony.org.domain.Shop;
import cn.jsony.org.mapper.EmployeeMapper;
import cn.jsony.org.mapper.ShopMapper;
import cn.jsony.pet.domain.Pet;
import cn.jsony.pet.domain.SearchMasterMsg;
import cn.jsony.pet.domain.SearchMasterMsgAuditLog;
import cn.jsony.pet.mapper.PetMapper;
import cn.jsony.pet.mapper.SearchMasterMsgAuditLogMapper;
import cn.jsony.pet.mapper.SearchMasterMsgMapper;
import cn.jsony.pet.query.SearchMasterMsgQuery;
import cn.jsony.pet.service.ISearchMasterMsgService;
import cn.jsony.basic.service.impl.BaseServiceImpl;
import cn.jsony.user.domain.Logininfo;
import cn.jsony.user.domain.User;
import cn.jsony.user.mapper.UserMapper;
import org.assertj.core.internal.bytebuddy.implementation.bytecode.Throw;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private PetMapper petMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper logMapper;

    @Autowired
    private IBaiduAiAuditService BaiduAiAuditService;

    @Autowired
    private SearchMasterMsgMapper searchMasterMsgMapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private OrderPetAcquisitionMapper orderPetAcquisitionMapper;

    @Override
    @Transactional
    public AjaxResult publish(SearchMasterMsg searchMasterMsg, HttpServletRequest request) {
        /*
         * 1.把寻主消息装进数据库(获取userId)
         * 2.审核
         * 2.1审核文本(name和地址)和图片,百度智能审核
         *      成功:1改变状态
         *          2.添加审核日志
         *          3.把寻主消息推送给50km内的的店铺--如果50km内么有店铺--
         *          4.短信或者邮件通知员工去用户的地址上门拿宠物
         *      失败
         * */
        //1.把寻主消息装进数据库(获取userId)
        Logininfo logininfo = LoginContext.getLogininfo(request);
        User user = userMapper.loadBylogininfo(logininfo.getId());
        Long id = user.getId();
        searchMasterMsg.setUserId(id);
        searchMasterMsgMapper.save(searchMasterMsg);
        //2.审核
        //2.1审核文本(name和地址)和图片,百度智能审核
        Boolean aBoolean = BaiduAiAuditService.textAudit(searchMasterMsg.getTitle()+searchMasterMsg.getName() + searchMasterMsg.getAddress());
        Boolean aBoolean1 = BaiduAiAuditService.imageAudit(searchMasterMsg.getResources());

        if (aBoolean && aBoolean1){
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();

            log.setState(1);
            log.setMsgId(searchMasterMsg.getId());
            log.setNote("审核成功");
            logMapper.save(log);
            Point point = DistanceUtils.getPoint(searchMasterMsg.getAddress());
            System.out.println(point);
            Shop nearestShop = DistanceUtils.getNearestShop(point, shopMapper.loadAll());
            System.out.println(nearestShop);
            if (nearestShop!=null){
                //                SmsUtils.sendSms(nearestShop.getTel(),"你有新的订单，请到"+searchMasterMsg.getAddress()+"去接宠物");
                System.out.println("你有新的订单，请到"+"去接宠物");
                searchMasterMsg.setShopId(nearestShop.getId());
            }
            searchMasterMsg.setState(1);
            System.out.println(searchMasterMsg);
            searchMasterMsgMapper.update(searchMasterMsg);
            return new AjaxResult();
        }else {
            SearchMasterMsgAuditLog log = new SearchMasterMsgAuditLog();
            log.setState(0);
            log.setNote("审核失败");
            log.setMsgId(searchMasterMsg.getId());
            logMapper.save(log);
            return AjaxResult.me().setMsg("审核失败").setSuccess(false);
        }
    }

    @Override
    public PageList<SearchMasterMsg> userQuery(SearchMasterMsgQuery query, HttpServletRequest requestequest) {
        //获取用户的id
        Logininfo logininfo = LoginContext.getLogininfo(requestequest);
        User user = userMapper.loadBylogininfo(logininfo.getId());
        query.setUserId(user.getId());
        return super.queryPage(query);
    }

    @Override
    public PageList<SearchMasterMsg> toHandle(SearchMasterMsgQuery query,HttpServletRequest request) {
        //判断一个管理员是店铺管理员还是平台管理员
        Logininfo logininfo = LoginContext.getLogininfo(request);
        Employee employee = employeeMapper.loadByLogininfoId(logininfo.getId());
        if (employee.getShop_id()!=null){
            query.setShopId(employee.getShop_id());
        }
        return super.queryPage(query);
    }

    @Override
    public void reject(Long id) {
        //通过id将shopId置为null
        SearchMasterMsg searchMasterMsgById = searchMasterMsgMapper.loadById(id);

        searchMasterMsgById.setShopId(null);

        searchMasterMsgMapper.update(searchMasterMsgById);
    }

    @Override
    public void accept(Map<String, Object> params) {

        Long msgId = Long.valueOf(params.get("msgId").toString());
        //1.校验改寻主消息是否已经在处理，报错
        OrderPetAcquisition orderTmp = orderPetAcquisitionMapper.loadByMsgId(msgId);
        if (orderTmp!=null){
            throw new BusinessException("已经被接单，正在处理中！");
        }

        //处理人id
        Long handlerId = Long.valueOf(params.get("handler").toString());
        String note = params.get("note").toString();
        Employee handler = employeeMapper.loadById(handlerId);

        //1 创建寻主消息所对应宠物信息
        //1.1 获取寻主消息
        SearchMasterMsg searchMasterMsg = searchMasterMsgMapper.loadById(msgId);
        //1.2 保存宠物信息在数据库
        Pet pet = searchMasterMsg2Pet(searchMasterMsg);
        petMapper.save(pet);

        //2 创建宠物收购订单
        OrderPetAcquisition order = buildPetAcquisitionOrder(searchMasterMsg,handler,pet);
        orderPetAcquisitionMapper.save(order);

        //3 发送消息给对应的工作人员
        System.out.println(handler.getEmail()+"-->邮件通知：您有新的"+order.getOrderSn()+"订单要处理！");
        //System.out.println(handler.getPhone()+"-->短信通知：您有新的"+order.getOrderSn()+"订单要处理！");
    }

    private OrderPetAcquisition buildPetAcquisitionOrder(SearchMasterMsg searchMasterMsg, Employee handler,Pet pet) {
        OrderPetAcquisition order = new OrderPetAcquisition();
        String orderSn = CodeGenerateUtils.generateOrderSn(handler.getId());
        order.setOrderSn(orderSn);
        order.setDigest(searchMasterMsg.getName()+"的收购订单");
        //最后收购是当前时间+2两天
        long lastcomfirmtimeLong = System.currentTimeMillis()+1000*60*60*24*2;
        order.setLastcomfirmtime(new Date(lastcomfirmtimeLong));
        order.setState(0);
        order.setPrice(searchMasterMsg.getPrice());
        //        order.setPaytype(); //现金支付
        order.setPetId(pet.getId());
        order.setUserId(searchMasterMsg.getUserId());
        order.setShopId(pet.getShopId());
        order.setAddress(searchMasterMsg.getAddress());
        order.setEmpId(handler.getId());
        order.setSearchMasterMsgId(searchMasterMsg.getId());
        return order;
    }

    private Pet searchMasterMsg2Pet(SearchMasterMsg searchMasterMsg) {
        Pet pet = new Pet();
        pet.setName(searchMasterMsg.getName());
        pet.setResources(searchMasterMsg.getResources());
        pet.setTypeId(searchMasterMsg.getPetType());
        //就要获取处理人的店铺id
        pet.setShopId(searchMasterMsg.getShopId());
        pet.setUserId(searchMasterMsg.getUserId());
        pet.setSearchMasterMsgId(searchMasterMsg.getId());
        //用户发布时需要的价格 收购回来就是成本价
        pet.setCostprice(searchMasterMsg.getPrice());
        return pet;
    }
}
